// pages/videosound/videosound.js
const app = getApp();

Page({
  inputValue: "",
  data: {
    savedFilePath: "",
    total: 3, // 配音总数
    step: 0, // 当前配音
    isSpeaking: false, // 是否正在说话
    recordTempFilePath: "", // 录音临时缓存地址
    recordFrameList: [], // 所有录音片段
  },
  onReady() {
    this.videoContext = wx.createVideoContext("myVideo");
    this.recorderManager = wx.getRecorderManager(); // 录音对象
    this.innerAudioContext = wx.createInnerAudioContext(); // 播放对象
    this.data.mediaContainer = wx.createMediaContainer();
  },
  destroy() {
    this.videoContext.destroy();
  },
  bindPlaySourceSound() {
    console.log("1");
    this.videoContext.play();
  },
  bindPlaySeek(numberPostion) {
    this.videoContext.seek(20);
    this.videoContext.play();
  },
  recordCurrent() {
    //  参考 https://blog.csdn.net/qq_37257212/article/details/79093470
  },
  startRecord() {
    const options = {
      duration: 5000,
      sampleRate: 16000, // 采样率，有效值 8000/16000/44100
      numberOfChannels: 1, // 录音通道数，有效值 1/2
      encodeBitRate: 96000, // 编码码率
      format: "mp3", // 音频格式，有效值 aac/mp3
      frameSize: 50, // 指定帧大小，单位 KB
    };
    //开始录音
    this.recorderManager.start(options);
    this.recorderManager.onStart(() => {
      console.log("开始录音");
    });
    this.setData({
      isSpeaking: true,
    });
    //错误回调
    this.recorderManager.onError((res) => {
      console.log(res);
    });
  },
  endRecord() {
    this.recorderManager.onStop((res) => {
      if (res.duration < 1000) {
        wx.showToast({
          title: "录音时间太短",
        });
        return;
      } else {
        this.setData({
          isSpeaking: false,
        });
        this.data.recordTempFilePath = res.tempFilePath; // 文件临时路径

        let mt = this.data.mediaContainer.extractDataSource({
          source: res.tempFilePath,
          success: (mt) => {
            this.data.audioKind = mt.tracks[0];
            this.data.recordFrameList.push(mt.tracks[0]);
            this.data.mediaContainer.addTrack(this.data.audioKind);
          },
          fail: (err) => {
            console.log(err);
          },
        });
        // this.uploadFileRecord(res);
      }
    });
    this.recorderManager.onError((res) => {
      console.log("小伙砸你录音失败了！");
    });
  },
  bindPlayRecord(e) {
    var that = this;
    this.innerAudioContext.src = this.data.recordTempFilePath;
    this.innerAudioContext.play();
    this.innerAudioContext.obeyMuteSwitch = false;
    this.innerAudioContext.onEnded((res) => {
      that.innerAudioContext.stop();
    });
  },
  // 开始合成。真机可以。跳转页面后的缓存视频已经去掉了音频通道,
  bindComposeRecord() {
    this.toNextPage();
  },
  toNextPage() {
    wx.navigateTo({
      url: "/pages/videoresult/videoresult?src=" + this.data.savedFilePath,
    });
  },
  uploadFileRecord(res) {
    wx.showLoading({
      title: "发送中...",
    });
    var tempFilePath = res.tempFilePath; // 文件临时路径
    console.log("文件临时路径", tempFilePath);

    wx.uploadFile({
      url: "", //上传服务器的地址
      filePath: tempFilePath, //临时路径
      name: "file",
      header: {
        contentType: "multipart/form-data", //按需求增加
      },
      formData: null,
      success: function (res) {
        console.log("上传成功");
        wx.hideLoading();
        that.setData({
          recordTempFilePath: tempFilePath,
        });
      },
      fail: function (err) {
        wx.hideLoading();
        console.log(err.errMsg); //上传失败
      },
    });
  },
  // wxfile://tmp_9ded76d75506015bafb1c30d49d66827f6909af54e256aac.mp4
  chooseVideo: function () {
    wx.chooseVideo({
      sourceType: ["album", "camera"],
      maxDuration: 60,
      camera: "back",
      success: (res) => {
        let videoPath = res.tempFilePath;

        let mt = this.data.mediaContainer.extractDataSource({
          source: videoPath,
          success: (mt) => {
            console.log(mt);
            this.data.videoKind = mt.tracks[1];
            // this.data.audioKind = mt.tracks[0]; // 视频中的音频抽出来
            this.data.mediaContainer.addTrack(this.data.videoKind);
            this.exportVideoMedia();
          },
          fail: (err) => {
            console.log(err);
          },
        });
      },
      fail: (err) => {
        console.log(err);
      },
    });
  },
  exportVideoMedia() {
    var that = this;
    //3.导出视频
    this.data.mediaContainer.export({
      success: (result) => {
        console.log(result);
        let tempArr1 = result.tempFilePath.split("//");
        let tempArr2 = tempArr1[1].split("/");
        let tempArr3 = tempArr2[tempArr2.length - 1].split(".");
        let tempString2 = "";
        for (let i = 0; i < tempArr2.length - 1; i++) {
          tempString2 += tempArr2[i] + "/";
        }
        let newPath =
          tempArr1[0] +
          "//" +
          tempString2 +
          new Date().getTime() +
          "." +
          tempArr3[1];
        // 导出新视频的名字每次都是一样的，估计有缓存什么的，我用时间戳重命名新导出的文件
        var filemanage = wx
          .getFileSystemManager()
          .renameSync(result.tempFilePath, newPath);

        wx.saveFile({
          tempFilePath: newPath, // 传入一个本地临时文件路径
          success(res) {
            console.log(res.savedFilePath); // res.savedFilePath 为一个本地缓存文件路径
            that.data.savedFilePath = res.savedFilePath;
          },
        });
        wx.downloadFile({
          tempFilePath: newPath, // 传入一个本地临时文件路径
          success(res) {
            console.log(res); // res.savedFilePath 为一个本地缓存文件路径
          },
        });

        // 4.移除内容，清空容器
        this.data.mediaContainer.removeTrack(this.data.videoKind);
        this.data.mediaContainer.removeTrack(this.data.audioKind);
      },
    });
  },
  playVideo() {
    // const myaudio = wx.createInnerAudioContext();
    // myaudio.src = "../../images/audio.mp3";
    // const that = this;
    // myaudio.play();
    // this.setData({ isplay: true });
    // var time = that.data.time;
    // console.log("倒计时开始");
    // var interval = setInterval(function () {
    //   myaudio.currentTime;
    //   myaudio.onTimeUpdate(() => {
    //     console.log(myaudio.duration); //总时长
    //     console.log("播放时间:", myaudio.currentTime); //当前播放进度
    //     var audioTime = myaudio.currentTime;
    //     that.setData({ currentTime: audioTime });
    //   });
    //   // 条件达到时停止定时器
    //   if (that.data.currentTime >= 10) {
    //     console.log("归0~~~", that.data.currentTime);
    //     clearInterval(interval);
    //     console.log("99999");
    //     // 暂停音频
    //     myaudio.pause();
    //     // 结束语音播放
    //     // wx.stopVoice()
    //     that.setData({ isplay: false });
    //     wx.showModal({
    //       title: "温馨提示!",
    //       content: "您当前最多只能试听前10秒的内容!请付费!",
    //       success(res) {
    //         if (res.confirm) {
    //           console.log("用户点击确定");
    //         } else if (res.cancel) {
    //           console.log("用户点击取消");
    //         }
    //       },
    //     });
    //   }
    // }, 1000);
    // that.setData({
    //   interval: interval,
    // });
    //  ======================================
  },
  getLocalFilePath() {
    var fs = wx.getFileSystemManager();
  },
  sliceSound() {},
});
